package com.blb.http;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 文件下载
 */
public class DownloadDemo {

    public static final String SAVE_PATH = "D:\\home\\";

    /**
     * 文件下载
     */
    public void download(String urlStr,String fileName){
        //创建URL对象
        try {
            URL url = new URL(urlStr);
            //获得连接对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置连接超时
            connection.setConnectTimeout(3000);
            //判断正常连接
            if(connection.getResponseCode() == 200) {
                try (
                        //获得输入流
                        InputStream inputStream = connection.getInputStream();
                        //本地输出流
                        OutputStream outputStream = new FileOutputStream(SAVE_PATH + fileName);
                ) {
                    //定义缓冲区
                    byte[] buffer = new byte[1024];
                    //每次读的长度
                    int len = 0;
                    //循环读取数据，写入到本地文件
                    while ((len = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                    System.out.println(fileName + "下载完毕");
                    Runtime.getRuntime().exec("mspaint " + SAVE_PATH + fileName);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new DownloadDemo().download("https://t7.baidu.com/it/u=3676218341,3686214618&fm=193&f=GIF","meinv.jpg");
    }
}
